// 文件：Assets/Editor/SheZiWangLoAutoUpdater.cs
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using Debug = UnityEngine.Debug;

[InitializeOnLoad]
public static class SheZiWangLoAutoUpdater
{
    private static readonly string repoUrl   = "https://gitee.com/shurongsen/unity-ue-maker.git";
    private const    string assetRoot       = "Assets/SheZiWangLoEditor";
    private static readonly string gitExe   = "/usr/bin/git";

    static SheZiWangLoAutoUpdater()
    {
        EditorApplication.delayCall += RunGitSync;
    }

    private static void RunGitSync()
    {
        return;
        string assetsPath = Application.dataPath;
        string repoPath   = Path.Combine(assetsPath, "SheZiWangLoEditor");
        bool   hasGitRepo = Directory.Exists(Path.Combine(repoPath, ".git"));

        if (!File.Exists(gitExe) || !hasGitRepo)
        {
            Debug.LogError("[AutoUpdater] Git 不可用或仓库不存在，全部标记为 ❌");
            UpdateGitIcons(markAllUnsynced: true);
            return;
        }

        // clone 或 pull
        if (!hasGitRepo)
        {
            Debug.Log("[AutoUpdater] 仓库不存在，开始 clone");
            if (!RunGitCommand(gitExe, $"clone {repoUrl} .", repoPath))
            {
                Debug.LogError("[AutoUpdater] git clone 失败，全部标记为 ❌");
                UpdateGitIcons(markAllUnsynced: true);
                return;
            }
        }
        else
        {
            Debug.Log("[AutoUpdater] 开始 git pull");
            if (!RunGitCommand(gitExe, "pull", repoPath))
                Debug.LogError("[AutoUpdater] git pull 失败");
        }

        UpdateGitIcons();
    }

    private static void UpdateGitIcons(bool markAllUnsynced = false)
    {
        // 读现有映射
        string prefsKey = FolderIconManager.kEditorPrefsKey;
        string json     = EditorPrefs.GetString(prefsKey, "");
        var    wrapper  = string.IsNullOrEmpty(json)
            ? new FolderIconManager.MappingList()
            : JsonUtility.FromJson<FolderIconManager.MappingList>(json);

        // 找到所有 GUID（包含文件和文件夹）
        string[] guids = AssetDatabase.FindAssets("", new[] { assetRoot });
        wrapper.list.RemoveAll(m => guids.Contains(m.targetGUID));

        // 获取未同步文件列表
        HashSet<string> changed = new HashSet<string>();
        if (!markAllUnsynced)
        {
            string status = RunGitCommandGetOutput(gitExe, "status --porcelain", Path.Combine(Application.dataPath, "SheZiWangLoEditor"));
            foreach (var line in status.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
            {
                // 格式："XY path/to/file"
                var rel = line.Substring(3).Replace("\\", "/");
                changed.Add(rel);
            }
        }

        // 新的图标路径
        string checkPath = "Assets/SheZiWangLoEditor/icon/check.png";
        string crossPath = "Assets/SheZiWangLoEditor/icon/cross.png";
        string checkGUID = AssetDatabase.AssetPathToGUID(checkPath);
        string crossGUID = AssetDatabase.AssetPathToGUID(crossPath);

        foreach (var guid in guids)
        {
            string assetPath = AssetDatabase.GUIDToAssetPath(guid);
            string relPath   = assetPath.Substring(assetRoot.Length + 1).Replace("\\", "/");

            bool isUnsynced = markAllUnsynced;
            if (!markAllUnsynced)
            {
                if (AssetDatabase.IsValidFolder(assetPath))
                {
                    // 文件夹：如果其下任何一个文件在 changed 中，则标 unsynced
                    isUnsynced = changed.Any(c => c.StartsWith(relPath + "/"));
                }
                else
                {
                    // 普通文件
                    isUnsynced = changed.Contains(relPath);
                }
            }

            wrapper.list.Add(new FolderIconManager.IconMapping
            {
                targetGUID = guid,
                iconGUID   = isUnsynced ? crossGUID : checkGUID
            });
        }

        EditorPrefs.SetString(prefsKey, JsonUtility.ToJson(wrapper));
        FolderIconOverride.ReloadIcons();
    }

    private static bool RunGitCommand(string exe, string args, string cwd)
    {
        try
        {
            var p = new Process {
                StartInfo = {
                    FileName            = exe,
                    Arguments           = args,
                    WorkingDirectory    = cwd,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute     = false,
                    CreateNoWindow      = true
                }
            };
            p.Start();
            p.WaitForExit();
            return p.ExitCode == 0;
        }
        catch (Exception ex)
        {
            Debug.LogError("[AutoUpdater] Git 命令异常: " + ex.Message);
            return false;
        }
    }

    private static string RunGitCommandGetOutput(string exe, string args, string cwd)
    {
        try
        {
            var p = new Process {
                StartInfo = {
                    FileName            = exe,
                    Arguments           = args,
                    WorkingDirectory    = cwd,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute     = false,
                    CreateNoWindow      = true
                }
            };
            p.Start();
            string outp = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            return outp;
        }
        catch (Exception ex)
        {
            Debug.LogError("[AutoUpdater] 获取 Git 输出异常: " + ex.Message);
            return "";
        }
    }
}
#endif